package com.uidp.ui;

import java.net.MalformedURLException;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.acsior.sbc.exception.BusinessException;
import com.acsior.sbc.exception.SearchException;
import com.acsior.wu.bean.MBUserBase;
import com.acsior.wu.bean.utils.MBManager;
import com.acsior.wu.menu.model.MenuEntry;
import com.acsior.wu.menu.model.MenuModel;
import com.acsior.wu.messanger.Messenger;
import com.uidp.bundle.Messages;
import com.uidp.domain.Users;
import com.uidp.security.IUser;
import com.uidp.security.SecurityUserManager;
import com.uidp.uitils.MBSetup;
import com.uidp.uitils.ManagedBeans;
import com.uidp.uitils.NavOutcomes;
import com.uidp.uitils.TopMenu;

public class MBUsers extends MBUserBase {

	/**
	 * Парола
	 */
	private String password;

	/**
	 * Модел на главното меню
	 */
	private MenuModel topMenuModel;

	/**
	 * Потр. име
	 */
	private String userName;

	/**
	 * @see com.acsior.wu.bean.MBUserBase#getPassword()
	 */
	@Override
	public String getPassword() {
		return this.password;
	}

	/**
	 * При вход изгражда модела на менюто
	 * 
	 * @return MenuModel
	 */
	public MenuModel getTopMenuModel() {
		return this.topMenuModel != null ? this.topMenuModel : new MenuModel(
				"Няма достъп до менюта");
	}

	/**
	 * Връща текущия потребител
	 * 
	 * @return User
	 */
	public Users getUser() {
		return SecurityUserManager.getInstance().getCurrentUser();
	}

	/**
	 * @see com.acsior.wu.bean.MBUserBase#getUserInfo()
	 */
	@Override
	public String getUserInfo() {
		return getUser() != null ? getUser().getFirstName() + " "
				+ getUser().getFamily() : "";
	}

	/**
	 * @see com.acsior.wu.bean.MBUserBase#getUserName()
	 */
	@Override
	public String getUserName() {
		return this.userName;
	}

	/**
	 * @see com.acsior.wu.bean.MBUserBase#login()
	 */
	@Override
	public String login() {

		if (isValid()) {
			try {
				IUser user = Users.searchActiveByUserName(getUserName());
				if (user.isPasswordSame(getPassword())) {
					boolean isLogged = SecurityUserManager.getInstance().login(
							(Users) user);
					if (isLogged) {
						buildTopMenuModel();
						return navigate(NavOutcomes.home);
					}
					Messenger.addErrorMessage(Messages.LOGIN_UNSUCCESFUL);
				}
				Messenger.addErrorMessage(Messages.PWD_INVALID);
			} catch (BusinessException e) {
				Messenger.addException(e);
			} catch (SearchException e) {
				Messenger.addException(e);
			}
		}
		return "";
	}

	/**
	 * @see com.acsior.wu.bean.MBUserBase#logout()
	 */
	@Override
	public String logout() {
		// SecurityUserManager.getInstance().logout();
		return navigate(NavOutcomes.login);
	}

	/**
	 * @see com.acsior.wu.bean.MBUserBase#navToHome()
	 */
	@Override
	public String navToHome() {
		return navigate(NavOutcomes.home);
	}

	/**
	 * @see com.acsior.wu.bean.MBUserBase#setPassword(java.lang.String)
	 */
	@Override
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @see com.acsior.wu.bean.MBUserBase#setUserName(java.lang.String)
	 */
	@Override
	public void setUserName(String userName) {
		this.userName = userName;
	}

	private void buildTopMenuModel() {
		HttpServletRequest req = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
		String webappURL = "http://" + req.getServerName() + ":"
				+ req.getServerPort() + req.getContextPath();

		this.topMenuModel = new MenuModel("menu");
		try {
			TopMenu[] MENU_NODES = TopMenu.values();
			for (TopMenu t : MENU_NODES) {
				// Tuk zarejda menuto spored rolite !!!
				// for (String res : getUser().getAllowedResources()) {
				// if (t.getSysName().equals(res)) {
				this.topMenuModel.addEntry(new MenuEntry(t.getDisplayName(),
						getURL(webappURL, t.getSysName()), t.getOrdering()));
				// }
				// }
			}

			MBSetup setup = (MBSetup) MBManager
					.findBeanInCtx(ManagedBeans.setup);
			setup.setTopMenuModel(topMenuModel);
		} catch (MalformedURLException e) {
			Messenger.addException(e);
		}
	}

	private String getURL(String webappURL, String path) {
		return webappURL + path + ".jsf";
	}

	/**
	 * Валидира въведените данни
	 * 
	 * @return boolean
	 */
	private boolean isValid() {
		boolean isValid = true;
		if (StringUtils.isEmpty(getUserName())) {
			isValid = false;
			Messenger.addErrorMessage(Messages.USERNAME_MISSING);
		}
		if (StringUtils.isEmpty(getPassword())) {
			isValid = false;
			Messenger.addErrorMessage(Messages.PWD_MISSING);
		}
		return isValid;
	}

}
